<template>
  <div class="app-container">
    <el-divider>
      <div class="my-divider">基础信息</div>
    </el-divider>

    <el-form
      :model="form"
      ref="form"
      size="small"
      label-width="80px"
      label-position="left"
      :rules="rules"
    >
      <el-form-item label="BOM版本" prop="bomVersion">
        <el-input
          v-model="form.bomVersion"
          placeholder="请输入BOM版本"
          clearable
          class="my-input"
        />
      </el-form-item>
      <el-form-item label="产品名称" prop="bomPdCode">
        <el-input
          :value="selectedProduct.pdName"
          class="my-input"
          disabled
        />
      </el-form-item>
      <el-form-item label="产品编号">
        <el-input
          :value="selectedProduct.pdCode"
          :disabled="true"
          class="my-input"
        />
      </el-form-item>
      <el-form-item label="规格型号">
        <el-input
          :value="selectedProduct.pdSpecType"
          :disabled="true"
          class="my-input"
        />
      </el-form-item>
      <el-form-item label="单位">
        <el-input
          :value="selectedProduct.gbsGoodUnit ? selectedProduct.gbsGoodUnit.guName: ''"
          :disabled="true"
          class="my-input"
        />
      </el-form-item>
      <el-form-item label="日产量" prop="bomDailyOutput">
        <el-input-number
          v-model="form.bomDailyOutput"
        />
      </el-form-item>
      <el-form-item label="备注" prop="bomDesc" class="my-desc">
        <el-input
          type="textarea"
          :autosize="{ minRows: 3 }"
          placeholder="请输入备注"
          v-model="form.bomDesc"
        />
      </el-form-item>
    </el-form>

    <el-divider>
      <div class="my-divider">物料配件</div>
    </el-divider>
    <el-button type="primary" @click="handleToAddBomMaterial">添加</el-button>
    <el-button type="primary" plain :disabled="!removeGoods || removeGoods.length === 0"
               @click="handleRemoveBomMaterial"
    >移除
    </el-button>
    <el-table
      :data="selectedMaterials"
      @selection-change="selectChangeRemoveGood"
    >
      <el-table-column
        type="selection"
        align="center"
      />
      <el-table-column
        type="index"
        align="center"
        label="序号"
      />
      <el-table-column label="物料编码" align="center" prop="pdCode" />
      <el-table-column label="物料名称" align="center" prop="pdName" />
      <el-table-column label="规格型号" align="center" prop="pdSpecType" />
      <el-table-column label="单位" align="center" prop="gbsGoodUnit.guName">
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="small"
            @click="handleRBomMaterialRow(scope.$index, selectedMaterials)"
          >
            移除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-divider>
      <div class="my-divider">工艺路线</div>
    </el-divider>
    <div v-if="form.bomPdCode && form.bomRoute && form.bomRoute !== '0'">
      <el-descriptions :column="2" v-if="route">
        <el-descriptions-item label="工艺路线名称">{{ route.prouteName }}</el-descriptions-item>
        <el-descriptions-item label="工艺路线编号">{{ route.prouteCode }}</el-descriptions-item>
      </el-descriptions>
      <el-tabs v-if="routeProcedures && routeProcedures.length > 0">
        <el-tab-pane v-for="(tab, index) in routeProcedures"
                     :key="tab.procedureCode"
                     :label="tab.procedureName"
        >
          <span slot="label">
            <MyTabPaneLabel :prefix-num="index + 1" :content="tab.procedureName" />
          </span>
          <el-button type="primary" @click="handleToAddMaterial(tab)">添加</el-button>
          <el-table
            :data="procedureMaterials[tab.procedureCode]"
          >
            <el-table-column
              type="selection"
              align="center"
            />
            <el-table-column type="index" align="center" label="序号" />
            <el-table-column label="物料编号" align="center" prop="pdCode" />
            <el-table-column label="物料名称" align="center" prop="pdName" />
            <el-table-column label="规格型号" align="center" prop="pdSpecType" />
            <el-table-column label="单位" align="center" prop="gbsGoodUnit.guName" />
            <el-table-column label="使用量" align="center" prop="procedureMNum" width="150">
              <template slot-scope="scope">
                <el-input-number
                  v-model="scope.row.procedureMNum"
                  style="width: 135px"
                  size="small"
                />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  v-hasPermi="['gbs:bom:edit']"
                  @click="handleRPMaterialRow(procedureMaterials[tab.procedureCode], scope.$index)"
                >移除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-empty v-else-if="form.bomPdCode && !form.bomRoute || form.bomRoute === '0'"
              description="该产品还没有工艺路线"
    />
    <el-empty v-else description="请选择产品" />

    <!-- 提交按钮 -->
    <MyConfirmBtnGroup :after-cancel-open-page="backPage" :ok-event="submitForm" />

    <!--    当前的产品选择物料配件-->
    <MyGoodDialog title="选择物料配件"
                  v-model="materialsDialogVisible"
                  :goods.sync="selectedMaterials"
                  :show-tabs="true"
                  :single-mode="false"
                  show-content="both"
    />

    <!--    当前的tab选择物料配件-->
    <MyGoodDialog title="选择物料配件"
                  v-model="tabDialogVisible"
                  :goods.sync="procedureMaterials[currentTab.procedureCode]"
                  :list-data="selectedMaterials"
                  :show-tabs="false"
                  :single-mode="false"
                  show-content="both"
                  :append-to-body="true"
    />
  </div>
</template>

<script>
import MyConfirmBtnGroup from '@/components/MyConfirmBtnGroup/index.vue'
import MyPopoverBtn from '@/components/MyPopoverBtn/index.vue'
import MyGoodDialog from '@/components/MyGoodDialog/index.vue'
import MyRadio from '@/components/MyRadio/index.vue'
import MyTabPaneLabel from '@/components/MyTabPaneLabel/index.vue'
import { addBom } from '@/api/yyj/gbs/bom'
import { listProcedureMaterial } from '@/api/yyj/pbs/procedureMaterial'
import { listGood } from '@/api/yyj/gbs/good'

export default {
  name: 'SonBomChange',
  components: { MyTabPaneLabel, MyRadio, MyGoodDialog, MyPopoverBtn, MyConfirmBtnGroup },
  dicts: ['gbs_good_type', 'gbs_good_attr'],
  data() {
    return {
      backPage: '',
      materialsDialogVisible: false,
      tabDialogVisible: false,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        bomVersion: [
          { required: true, message: 'BOM版本不能为空', trigger: 'blur' }
        ],
        bomRoute: [
          { required: true, message: '工艺路线不能为空', trigger: 'blur' }
        ],
        bomDailyOutput: [
          { required: true, message: '日产量不为空', trigger: 'blur' }
        ]
      },
      selectedProduct: {},
      // 添加的物料配件
      selectedMaterials: [],
      // 准备移除的物料配件
      removeGoods: [],
      // 选择的工艺路线
      route: {},
      // 此工艺路线下的工序 routeProcedures 需要从物料配件中添加
      routeProcedures: [],
      // 工序物料
      procedureMaterials: [],
      // 当前的tab
      currentTab: {},
      bomCode: '',
      bomVersion: ''
    }
  },
  computed: {
    getGbsGoodType() {
      return this.dict.type.gbs_good_type
    },
    getGbsGoodAttr() {
      return this.dict.type.gbs_good_attr
    }
  },
  watch: {
    'form.bomRoute': {
      handler(nVal) {
        this.getRoute(nVal)
      },
      immediate: true
    }
  },
  created() {
    const pdCode = this.$route.params.pdCode
    this.bomCode = this.$route.query.bomCode
    this.bomVersion = this.$route.query.bomVersion
    this.backPage = `/gbs/bom-detail?bomCode=${this.bomCode}&bomVersion=${this.bomVersion}`
    this.getPdDetail(pdCode)
  },
  methods: {
    // 获取good信息
    async getPdDetail(pdCode) {
      const res = await listGood({
        pdCode
      })
      this.selectedProduct = res.rows[0]
      this.form.bomPdCode = this.selectedProduct.pdCode
      this.form.bomRoute = this.selectedProduct.pdProuteCode
    },
    // 查询工艺路线
    async getRoute(routeCode) {
      const res = await listProcedureMaterial({
        pmProuteCode: routeCode,
        procedureMBom: this.form.bomCode,
        procedureMBV: this.form.bomVersion
      })
      if (!res.data) {
        return
      }
      this.routeProcedures = res.data
      this.route = res.route
      this.procedureMaterials = res.procedureMaterials
    },
    // 准备移除物料配件
    selectChangeRemoveGood(selection) {
      this.removeGoods = selection
    },
    // 移除物料配件
    handleRemoveBomMaterial() {
      this.removeGoods.forEach(e1 => {
          this.selectedMaterials =
            this.selectedMaterials.filter(e2 => e2.pdCode !== e1.pdCode)
        }
      )
    },
    // 打开物料配件弹窗
    handleToAddBomMaterial() {
      this.materialsDialogVisible = true
    },
    // 移除物料配件
    handleRBomMaterialRow(index, rows) {
      rows.splice(index, 1)
    },
    // 添加工序物料
    handleToAddMaterial(tab) {
      if (!this.selectedMaterials || this.selectedMaterials.length <= 0) {
        this.$modal.msgWarning('请先选择物料')
        return
      }
      this.currentTab = tab
      this.tabDialogVisible = true
    },
    // 行 移除工序物料
    handleRPMaterialRow(material, index) {
      material.splice(index, 1)
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(async valid => {
        if (valid) {
          if (!this.form.bomRoute || this.form.bomRoute === '0') {
            this.$modal.msgError('添加失败，该产品还没有工艺路线')
            return
          }
          const gbsBomMaterials = this.selectedMaterials.map(e => {
            return {
              bmBomCode: this.form.bomCode,
              bmBomVersion: this.form.bomVersion,
              bmMaterialCode: e.pdCode,
              bmMBomCode: this.bomCode,
              bmMBomVersion: this.bomVersion
            }
          })
          const pbsProcedureMaterials = []
          for (let k in this.procedureMaterials) {
            this.procedureMaterials[k].forEach(e => {
              pbsProcedureMaterials.push({
                pdCode: e.pdCode,
                procudureCode: k,
                pmProuteCode: this.form.bomRoute,
                procudereMNum: e.procudereMNum,
                procedureMBom: this.form.bomCode,
                procedureMBV: this.form.bomVersion
              })
            })
          }
          const data = {
            gbsBom: this.form,
            gbsBomMaterials: gbsBomMaterials,
            pbsProcedureMaterials: pbsProcedureMaterials
          }
          this.$modal.loading('正在提交...')
          await addBom(data)
          this.$modal.msgSuccess('新增成功')
          this.afterSubmit()
        }
      })
    },
    afterSubmit() {
      this.$tab.closeOpenPage()
      this.reset()
      this.$tab.refreshPage({
        path: this.backPage
      })
      this.$modal.closeLoading()
    },
    // 表单重置
    reset() {
      this.form = {
        bomCode: null,
        bomPdCode: null,
        gbsGood: {},
        isDefault: null,
        bomVersion: null,
        bomDailyOutput: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        bomDesc: null,
        bomRoute: null
      }
      this.resetForm('form')
    }
  }
}
</script>

<style scoped lang="scss">
@import '@/assets/styles/yyj/change';
</style>
